package com.hanhai.zrb.mobile.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.hanhai.common.file.fastdfs.StorePath;
import com.hanhai.common.file.fastdfs.service.IStorageClientService;
import com.hanhai.common.file.fastdfs.service.ITrackerClientService;
import com.hanhai.common.result.ImgUploadResult;
import com.hanhai.common.util.MultipartFileValidator;
import com.hanhai.common.web.controller.BaseController;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.mobile.result.BaseApiResult;
import com.hanhai.zrb.mobile.util.AvatarImgUploadUtil;
import com.hanhai.zrb.mobile.util.FrontLoginUtil;
import com.hanhai.zrb.model.common.BaseUser;
import com.hanhai.zrb.model.user.User;

@RestController
@RequestMapping("/avatarApi")
public class AvatarUploadApiController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(getClass());
	/*@Value("#{configProperties['upload.img.path']}")
	private String upload_img_path;*/
	
	/*@Value("#{configProperties['zhaorongbao.img.url']}")
	private String img_url;*/
	@Resource
	private UserService userService ;
	
	private String avatarFolder = "user_avatar";
	
	@Autowired
	private ITrackerClientService trackerClientService;

	@Autowired
	private IStorageClientService storageClientService;

	
	@RequestMapping(value="index")
	public String  index(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return "indexeeee";
	}
	
	private String storeFile(File file) throws IOException{
		byte[] bytes = FileUtils
				.readFileToByteArray(file);
		StorePath storePath = storageClientService.uploadFile("group1",
				new ByteArrayInputStream(bytes), bytes.length, "jpg");
		return storePath.getPath();
	}
	
	private String storeFile(MultipartFile file) throws IOException{
		byte[] bytes = file.getBytes();
		StorePath storePath = storageClientService.uploadFile("group1",
				new ByteArrayInputStream(bytes), bytes.length, "jpg");
		return storePath.getGroup()+"/"+storePath.getPath();
	}
	
	@RequestMapping(value="fileUpload")
	public BaseApiResult fileUpload(MultipartHttpServletRequest request,HttpServletResponse response) throws Exception{	
		BaseUser baseUser = FrontLoginUtil.getCurrentUser();
		BaseApiResult ret = new BaseApiResult();
		if(null!=baseUser){
		try {
			
			MultipartFile file = request.getFile("uploadExcel");
			 /*MultipartFileValidator  validator = new MultipartFileValidator();  
	         validator.setAllowedContentTypes(new String[] { "image/jpeg",  
	         "image/pjpeg","image/png","image/x-png" });*/
	         if(null != file && !file.isEmpty()){
	        	//	validator.validate(file);
	        		String path = storeFile(file);
	    			
	    			User user  = new User();
					user.setUid(baseUser.getUid());
					user.setAvatar(path);
					userService.update(user);
					ret.setMsg("上传头像成功");
					ret.setRes(1);	
					return ret;
	         }
	         ret.setMsg("上传头像失败，请稍候再试");
			ret.setRes(0);
			return ret;
	        		
			/*ImgUploadResult	result = AvatarImgUploadUtil.saveUploadFile(request,upload_img_path);
			//获取图片URL路径
			//ImgUploadResult result = this.saveUploadAvatar(request, upload_img_path,avatarFolder, baseUser.getUid());
			if(result.isSuccess()){
				User user  = new User();
				user.setUid(baseUser.getUid());
				Map<String,String> maps =new HashMap<String, String>();
				maps = result.getSuccessFinalFileNameInfoList();
				 for (Map.Entry<String, String> entry : maps.entrySet()) {
					   user.setAvatar(entry.getKey());  
				}
				userService.update(user);
				ret.setMsg("上传头像成功");
				ret.setRes(1);	
			}else{
				ret.setMsg("上传头像失败，请稍候再试");
				ret.setRes(0);
			}*/
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("do  AvatarImgUploadUtil.saveUploadFile exception", e);
			ret.setMsg("上传头像失败，请稍候再试");
			ret.setRes(0);
		}

	}else{
		ret.setMsg("请先登录在上传");
		ret.setRes(0);
	
	}
	return ret;

	}
	
	private ImgUploadResult saveUploadAvatar(HttpServletRequest request, String imagePath,String avatarFolder,Long uid) {
		
		ImgUploadResult result = new ImgUploadResult();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		//String finalFileName = "";
		List<String> finalFileNameList = new ArrayList<String>();
		
		Map<String,String> uploadNameList = new HashMap<String,String>();
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();
					String finalName = avatarFolder+File.separator+uid.toString();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (StringUtils.isNotEmpty(fileName)) {
				
						try {

							String path = imagePath + File.separator + finalName;
							File localFile = new File(path);
							file.transferTo(localFile);
							uploadNameList.put(fileName, finalName);
							finalFileNameList.add(finalName);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}

			}

		}
		if(uploadNameList.size()>0){
			result.setSuccess(true);
			result.setSuccessFinalFileNameInfoList(uploadNameList);
		}
		
		return result;
		
	}
}

